package com.android.djlmapp.activity.my;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.home.web.ForgetPwdActivity;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.dialog.TsDialog;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.token.TokenExpiredUtils;
import com.android.djlmapp.tools.global.Constants;
import com.android.djlmapp.tools.global.ConstantsValue;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.feihong.zhiwenlibrary.dialog.DJLM_PasswordDialog;
import com.feihong.zhiwenlibrary.dialog.PasswordDialogListener;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 绑定账号
 */
public class BundingZFBActivity extends BaseActivity {
    public static final String TAG = "djlm-my: ";

    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.top_notes)
    ImageView topNotes;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.tv_top_jump)
    TextView tvTopJump;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.bd_zhanghao)
    TextView bdZhanghao;
    @BindView(R.id.bd_name)
    TextView bdName;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.bd_num)
    EditText bdNum;
    @BindView(R.id.tv_top_sm)
    TextView tvTopSm;
    @BindView(R.id.tv_btm_sm)
    TextView tvBtmSm;
    @BindView(R.id.tv_sqzhk)
    TextView tvSqzhk;
    @BindView(R.id.ll_yhk)
    LinearLayout llYhk;
    @BindView(R.id.tv_zfb)
    TextView tvZfb;
    @BindView(R.id.tv_bund)
    TextView tvBund;
    private String mUrl = "";
    private String bd_smrz = "";
    private String bd_yhk = "";
    private String bd_zfb = "";
    private String bd_name = "";
    private String newName = ""; // 隐藏用户姓名
    private String num = "";
    private TsDialog tsDialog;
    private UserInfoUtils infoUtils;
    private int flag = 1; // 解除绑定的标记
    private Context mContext;
    private ProgressBar pb_paying;
    private String mNum;
    private Unbinder mUnbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bunding);
        mUnbinder = ButterKnife.bind(this);
        mContext = getActivity();

        initData();
        initView();
    }

    @Override
    protected void initData() {
        tsDialog = new TsDialog(this);
        tsDialog.setCanceledOnTouchOutside(true);
        tsDialog.setCancelable(true);
        tsDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                tvBund.setEnabled(true);
                return false;
            }
        });
    }

    @Override
    protected void initView() {
        homeIvReadpoint.setVisibility(View.GONE);
        topNotes.setVisibility(View.GONE);

        infoUtils = UserInfoUtils.getUserInfoUtilsInstance();
        bd_zfb = infoUtils.getBD_ZFB();
        bd_smrz = infoUtils.GetBDSMRZ();
        bd_name = infoUtils.GetRelName();

        // 支付宝
        tvName.setText("绑定支付宝账号");
        bdZhanghao.setText("请绑定您本人的支付宝账号");

        tvTopSm.setText("1:实名认证后才可绑定账号。");
        tvBtmSm.setText("2:绑定账号须与本人实名认证信息一致!否则无法绑定成功。");

        llYhk.setVisibility(View.GONE);
        tvZfb.setVisibility(View.VISIBLE);// 是支付宝才显示这个提示
        number.setText("账号");

        if (bd_name != null && !TextUtils.isEmpty(bd_name)) {
            if (bd_name.length() == 1) {
                newName = bd_name;
            } else if (bd_name.length() == 2) {
                newName = bd_name.replace(bd_name.substring(0, bd_name.length() - 1), "*");// 隐藏用户信息
            } else if (bd_name.length() == 3) {
                newName = bd_name.replace(bd_name.substring(0, bd_name.length() - 2), "*");// 隐藏用户信息
            } else if (bd_name.length() == 4) {
                newName = bd_name.replace(bd_name.substring(0, bd_name.length() - 2), "**");// 隐藏用户信息
            } else {
                newName = bd_name.replace(bd_name.substring(1, bd_name.length() - 1), "***");// 隐藏用户信息
            }
        }

        if ("0".equals(bd_zfb)) {
            bdNum.setCursorVisible(true);// 光标显示
            bdNum.setInputType(InputType.TYPE_CLASS_TEXT);
            if ("0".equals(bd_smrz)) {
                // 未实名认证,需要跳转实名认证界面(弹窗)
                tsDialog.show();
            } else {
                bdName.setText(newName);
            }
            mUrl = GlobalUrls.BD_ZFB;
            tvBund.setText("立即绑定");
            bdNum.setHint("请输入您的支付宝邮箱或手机号");

        } else {
            bdNum.setCursorVisible(false);// 光标隐藏
            bdNum.setInputType(InputType.TYPE_NULL);
            flag = 0;

            if (bd_zfb.contains("@")) {
                if(bd_zfb.length() > 4){
                    mNum = bd_zfb.replace(bd_zfb.substring(4, bd_zfb.indexOf("@")), "****");// 隐藏用户信息
                }else {
                    mNum = bd_zfb;
                }

            } else {
                if(bd_zfb.length() > 7){
                    mNum = bd_zfb.replace(bd_zfb.substring(3, 7), "****");// 隐藏用户信息
                }else{
                    mNum = bd_zfb;
                }


            }

            bdName.setText(newName);
            bdNum.setText(mNum);
            mUrl = GlobalUrls.JB_ZFB;
            tvBund.setText("解除绑定");
        }

    }

    @OnClick({R.id.tv_bund, R.id.tv_sqzhk, R.id.ll_top_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_top_back:
                finish();
                break;
            case R.id.tv_bund:
                closeKB();
                tvBund.setEnabled(false);
                num = bdNum.getText().toString().trim();
                if ("0".equals(bd_smrz)) { // 未实名认证并且不是解除绑定才弹出实名认证弹窗
                    // 未实名认证,需要跳转实名认证界面(弹窗)
                    tsDialog.show();
                } else {
                    if (flag != 0) { // 如果是未绑定,则需要弹出软键盘
                        // 绑定接口
                        if(num != null && !TextUtils.isEmpty(num)){
                            showKeyBoard(); // 密码键盘
                        }else{
                            ToastUtils.showShortToast(this, "请输入账号");
                        }
                    } else { // 如果是解绑则直接请求接口
                        // 绑定接口
                        getNet("","","");
                    }
                    tvBund.setEnabled(true);
                }
                break;
            case R.id.tv_sqzhk:
                // 绑定的地方要加个招行卡的申请链接..
                Uri uri = Uri.parse(GlobalUrls.ZHK_SQLJ);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                break;
        }

    }

    public void getNet(String pwd, String touch_pwd, String touch_num) {
        Log.i(TAG , "mUrl: " + mUrl +" num: " + num+" bd_name:" +bd_name+"pwd: " +pwd);

        MyApplication.getInstance().getHttpTools().EditBankAccount(num, bd_name, pwd, mUrl, touch_pwd,touch_num, new StringCallback() {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                Log.i(TAG, "getNet : " +response.body());

                tvBund.setEnabled(true);
                try {
                    parseJson(response.body(), pwd, touch_pwd, touch_num);
                } catch (Exception e) {
                    Log.i(TAG, "getNet 数据解析异常: " +e.toString());

                    ToastUtils.showShortToast(BundingZFBActivity.this, "数据解析异常" + e.toString());
                }
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<String> response) {
                super.onError(response);
                tvBund.setEnabled(true);
                ToastUtils.showShortToast(BundingZFBActivity.this, "请检查网络");
            }
        });

    }

    class BudInfo {
        public String code;
        public String msg;
        public String alipay;
    }

    private void parseJson(String s, String pwd, String touch_pwd, String touch_num) {
        Log.i(TAG, "parseJson: " + s);

        Gson gson = new Gson();
        BudInfo budInfo = gson.fromJson(s, BudInfo.class);

        if (budInfo != null) {
            int count = Integer.parseInt(budInfo.code);
            if (count < 1000) {
                ToastUtils.showShortToast(this, budInfo.msg);
                if (flag == 0) { // 解除绑定成功
                    bdNum.setCursorVisible(true);// 光标显示
                    bdNum.setInputType(InputType.TYPE_CLASS_TEXT);
                    flag = 1;
                    tvBund.setText("立即绑定");
                    bdNum.setText("");
                    infoUtils.setBD_ZFB("0"); // 更新支付宝绑定状态

                    mUrl = GlobalUrls.BD_ZFB;

                } else { // 绑定成功
                    if (passwordDialog != null) {
                        passwordDialog.dismiss();
                    }
                    bdNum.setCursorVisible(false);// 光标隐藏
                    bdNum.setInputType(InputType.TYPE_NULL);
                    flag = 0;
                    // 绑定成功
                    tvBund.setText("解除绑定");

                    if (bd_name != null && !TextUtils.isEmpty(bd_name)) {
                        if (bd_name.length() == 1) {
                            newName = bd_name;
                        } else if (bd_name.length() == 2) {
                            newName = bd_name.replace(bd_name.substring(0, bd_name.length() - 1), "*");// 隐藏用户信息
                        } else if (bd_name.length() == 3) {
                            newName = bd_name.replace(bd_name.substring(0, bd_name.length() - 2), "*");// 隐藏用户信息
                        } else if (bd_name.length() == 4) {
                            newName = bd_name.replace(bd_name.substring(0, bd_name.length() - 2), "**");// 隐藏用户信息
                        } else {
                            newName = bd_name.replace(bd_name.substring(1, bd_name.length() - 1), "***");// 隐藏用户信息
                        }
                    }

                    bdName.setText(newName);


                    mNum = budInfo.alipay;
                    if (mNum.contains("@")) {
                        if(mNum.length()> 4){
                            mNum = mNum.replace(mNum.substring(4, mNum.indexOf("@")), "****");// 隐藏用户信息
                        }
                    } else {
                        if(mNum.length()> 7) {
                            mNum = mNum.replace(mNum.substring(3, 7), "****");// 隐藏用户信息
                        }
                    }

                    mUrl = GlobalUrls.JB_ZFB;

                    infoUtils.setBD_ZFB(budInfo.alipay); // 更新支付宝绑定状态
                    bdNum.setText(mNum);
                }
            } else if (count == 1111) {
                new TokenExpiredUtils(mContext, new TokenExpiredUtils.RefreshTokenListener() {
                    @Override
                    public void refreshTokenSuc(String token) {

                        if (pwd.length() == 6) {
                            getNet( pwd, touch_pwd, touch_num);
                        } else {
                            getNet(Constants.getZhiWenNewPwd(mContext),
                                    Constants.getZhiWenTouchPwd(mContext),
                                    Constants.zhiWenNum);
                        }

                    }
                }).refreshServ();
            } else {
                if (flag != 0) {
                    // 显示订单提交失败
                    if (TextUtils.isEmpty(budInfo.msg)) {
                        passwordDialog.setState(R.mipmap.pay_er, "绑定失败");
                    } else {
                        passwordDialog.setState(R.mipmap.pay_er, budInfo.msg);
                    }
                } else {
                    ToastUtils.showShortToast(mContext, "err:" + budInfo.msg);
                }
            }
        }
    }

    /**
     * 初始化密码键盘
     */
    private void initKeyBord() {
        passwordDialog = new DJLM_PasswordDialog(this);
        passwordDialog.setCallBack(new PasswordDialogListener() {
            @Override
            public void onDoneInput(DJLM_PasswordDialog dialog, String pwd) {
                passwordDialog.showLoadingView();
                getNet(pwd, "", "");
            }

            @Override
            public void successFinger(DJLM_PasswordDialog dialog) {
                passwordDialog.showLoadingView();
//                String touch_pwd = PrefUtils.getString(ConstantsValue.ZHIWEN_KEY, "");
                getNet(Constants.getZhiWenNewPwd(mContext),
                        Constants.getZhiWenTouchPwd(mContext),
                        Constants.zhiWenNum);
            }

            @Override
            public void onBtnClick(int type) {
                if (type == 2) {
                    //忘记密码按钮点击
                    startActivity(new Intent(mContext, ForgetPwdActivity.class));
                }
            }
        });
    }

    private DJLM_PasswordDialog passwordDialog;

    /**
     * 弹出自定义输入键盘
     */
    private void showKeyBoard() {
        initKeyBord();
        passwordDialog.show(getSupportFragmentManager(), "支付");

        if (PrefUtils.getBoolean(ConstantsValue.ZHIWEN_STATE, false)
                && !TextUtils.isEmpty(PrefUtils.getString(ConstantsValue.ZHIWEN_KEY, ""))) {
            if (passwordDialog.isFingerprintEnable()) {
                passwordDialog.setEnableFinger(true);
            } else {
                passwordDialog.setEnableFinger(false);
            }

        } else {
            passwordDialog.setEnableFinger(false);
        }
        //隐藏余额
        passwordDialog.setGone(true);

    }

    TextWatcher phoneTextW = new TextWatcher() { // EditText变化监听

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.e(TAG, "------afterTextChanged------" + s.toString());

//            keyvalue = simNum.getText().toString();
//
//            //将光标移至文字末尾
//            simNum.setSelection(keyvalue.length());
//            if (!TextUtils.isEmpty(keyvalue)) {
//                if (window != null) {
//                    window.showBashOfAnchor(simNum, layoutGravity, 0, 0);
//                    getSimNumData(keyvalue, false);
//                }
//            } else {
//                if (popupWindow != null && popupWindow.isShowing()) {
//                    popupWindow.dismiss();
//                }
//            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tsDialog != null) {
            tsDialog.dismiss();
        }
        closeKB();
        mUnbinder.unbind();
    }

    private void  closeKB() {
        //关闭键盘
        try {
            View view = getWindow().peekDecorView();
            if (view != null) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        } catch (Exception e) {
        }
    }
}
